package com.example.handler;

import com.example.entity.CommonReqDTO;
import com.example.entity.Condition;
import com.example.mapper.DynamicSqlMapper;
import com.example.service.DataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class DynamicSqlProvider {

    private static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public String executeRawSql(Map<String, Object> params) {
        // 直接返回传入的SQL语句
        return (String) params.get("sql");
    }


    public String executeRawSql2(Map<String, Object> params) {
        // 直接返回传入的SQL语句
        Integer id = (Integer) params.get("id");
        System.out.println(id);
        return "select  * from test where id="+id;
    }


    public String executeSqlByMap(Map<String, Object> params) {
        String finalSql = null;
        String sql = (String) params.get("sql");

        CommonReqDTO reqDTO = (CommonReqDTO) params.get("reqDTO");

        Condition condition = reqDTO.getCondition();

        if(StringUtils.isEmpty(sql)){
            throw new RuntimeException("执行sql为空");
        }
        // 判断是存储过程
        if(sql.toLowerCase().startsWith("call")){
            finalSql = getProcedureSql(sql,condition);
        }
        // sql语句
        if(sql.toLowerCase().startsWith("select")){
            finalSql = getFinalSql(sql, condition);
        }
//        log.info("sourceSql:"+finalSql);
        System.out.println(finalSql);
        return finalSql;
    }


    // 处理存储过程

    /*** 参数顺序：
     * call test_pro(),直接调用名称，不需要添加参数，程序会自动添加参数
     *
     *  每个存储过程都会有下面的参数：
     *
     * (IN storeId VARCHAR(255),
     * IN productClassId VARCHAR(255),
     * IN supplierId VARCHAR(255),
     * IN startTime DATE,
     * IN endTime DATE,
     * IN startTimeTwo DATE,
     * IN endTimeTwo DATE)
     */
    private String getProcedureSql(String procedureName, Condition condition){

        //call test_pro()

        procedureName = procedureName.replace(")","");
        StringBuffer buffer  = new StringBuffer(procedureName);


        if(StringUtils.isEmpty(condition.getStoreId())){
            buffer.append("null").append(",");
        }else{
            buffer.append(handleParameter(condition.getStoreId())).append(",");
        }

        if(StringUtils.isEmpty(condition.getProductClassId())){
            buffer.append("null").append(",");
        }else{
            buffer.append(handleParameter(condition.getProductClassId())).append(",");
        }

        if(StringUtils.isEmpty(condition.getSupplierId())){
            buffer.append("null").append(",");
        }else{
            buffer.append(handleParameter(condition.getSupplierId())).append(",");
        }

        if(condition.getStartTime()==null){
            buffer.append("null").append(",");
        }else{
            buffer.append(handleParameter(condition.getStartTime())).append(",");
        }

        if(condition.getEndTime()==null){
            buffer.append("null").append(",");
        }else{
            buffer.append(handleParameter(condition.getEndTime())).append(",");
        }

        if(condition.getStartTimeTwo()==null){
            buffer.append("null").append(",");
        }else{
            buffer.append(handleParameter(condition.getStartTimeTwo())).append(",");
        }

        if(condition.getEndTimeTwo()==null){
            buffer.append("null");
        }else{
            buffer.append(handleParameter(condition.getEndTimeTwo()));
        }
        buffer.append(")");
        return buffer.toString();
    }


    private String getFinalSql(String sql, Condition condition) {
        if (condition != null) {
            if(condition.getStoreId()!=null && !condition.getStoreId().equals("")){
                sql = sql.replaceAll("#\\{storeId}", handleParameter(condition.getStoreId()));
            }
            if(condition.getProductClassId()!=null && !condition.getProductClassId().equals("")){
                sql = sql.replaceAll("#\\{productClassId}",handleParameter(condition.getProductClassId()));
            }
            if(condition.getSupplierId()!=null && !condition.getSupplierId().equals("")){
                sql = sql.replaceAll("#\\{supplierId}",handleParameter(condition.getSupplierId()));
            }
            if(condition.getStartTime()!=null){
                sql = sql.replaceAll("#\\{startTime}",handleParameter(condition.getStartTime().toString()));
            }
            if(condition.getEndTime()!=null){
                sql = sql.replaceAll("#\\{endTime}",handleParameter(condition.getEndTime().toString()));
            }
        }
        return sql;
    }


    // 处理参数
    private String handleParameter(Object param){
        if(param instanceof Integer){
            return param.toString();
        }else if(param instanceof String){
            return "'"+param+"'";
        }else if(param instanceof Date){
            return "'"+DEFAULT_FORMAT.format(param)+"'";
        }
        return param.toString();
    }


    public static void main(String[] args) {
        String sql = "call ";
    }

}

